<template>
  <el-dialog
    :title="groupTitle"
    :visible.sync="visible"
    width="80%"
    class="dialog-collective-registration"
    @close="handleClose"
  >
    <el-tabs v-model="groupActiveTab" type="card">
      <!-- 单位信息标签页 -->
      <el-tab-pane label="单位信息" name="unitInfo">
        <el-form ref="groupForm" :model="groupForm" :rules="groupRules" label-width="120px">
          <el-form-item label="单位名称">
            <el-input v-model="groupForm.unitName" placeholder="请输入单位名称" />
          </el-form-item>
          <el-form-item label="统一信用代码" prop="socialCreditCode">
            <el-input v-model="groupForm.socialCreditCode" placeholder="请输入统一信用代码" />
          </el-form-item>
          <el-form-item label="所属区域" prop="administrativeArea">
            <el-input v-model="groupForm.administrativeArea" placeholder="请输入所属区域" />
          </el-form-item>
          <el-form-item label="单位性质" prop="unitNature">
            <el-select v-model="groupForm.unitNature" placeholder="请选择单位性质">
              <el-option label="企业" value="enterprise" />
              <el-option label="事业单位" value="institution" />
              <el-option label="政府机关" value="government" />
            </el-select>
          </el-form-item>
          <el-form-item label="联系人" prop="contact">
            <el-input v-model="groupForm.contact" placeholder="请输入联系人姓名" />
          </el-form-item>
          <el-form-item label="联系电话" prop="unitPhonenumber">
            <el-input v-model="groupForm.unitPhonenumber" placeholder="请输入手机号码" />
          </el-form-item>
        </el-form>
      </el-tab-pane>

      <!-- 人员信息标签页 -->
      <el-tab-pane label="人员信息" name="personInfo">
        <el-form ref="personForm" :model="personForm" label-width="120px">
          <el-form-item label="培训类别">
            <el-select v-model="personForm.trainingType" placeholder="请选择培训类别">
              <el-option label="1" value="新训" />
              <el-option label="2" value="复训" />
            </el-select>
          </el-form-item>
          <el-form-item label="姓名">
            <el-input v-model="personForm.studentName" placeholder="请输入姓名" />
          </el-form-item>
          <el-form-item label="手机号码">
            <el-input v-model="personForm.phonenumber" placeholder="请输入手机号码" />
          </el-form-item>
          <el-form-item label="证件号码">
            <el-input v-model="personForm.idNumber" placeholder="请输入证件号码" />
          </el-form-item>
          <el-form-item label="工作单位">
            <el-input v-model="personForm.workUnit" placeholder="请输入工作单位" />
          </el-form-item>
          <el-form-item label="工作时间">
            <el-date-picker
              v-model="personForm.workPeriod"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            />
            <el-button type="text" @click="addWorkExperience">添加到工作简历</el-button>
          </el-form-item>
          <el-form-item label="工作简历">
            <el-textarea
              v-model="personForm.workResume"
              rows="3"
              placeholder="请输入工作简历内容"
            />
          </el-form-item>
        </el-form>
        <div style="margin-top: 20px; text-align: right;">
          <el-button type="primary" @click="continueAddPerson">继续添加</el-button>
        </div>
      </el-tab-pane>

      <!-- 已添加人员标签页 -->
      <el-tab-pane label="已添加人员" name="addedPersons">
        <el-table :data="personList" border>
          <el-table-column prop="studentName" label="姓名" width="120" />
          <el-table-column prop="phonenumber" label="手机号码" width="150" />
          <el-table-column prop="idNumber" label="证件号码" width="200" />
          <el-table-column prop="workUnit" label="工作单位" />
          <el-table-column label="操作" width="100">
            <template slot-scope="scope">
              <el-button
                type="text"
                size="small"
                @click="removePerson(scope.$index)"
                style="color: #f56c6c;"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>

    <div slot="footer">
      <el-button @click="prevStep" v-if="groupActiveTab !== 'unitInfo'">上一步</el-button>
      <el-button @click="nextStep" v-if="groupActiveTab === 'unitInfo'">下一步</el-button>
      <el-button @click="handleClose">取消</el-button>
      <el-button
        type="primary"
        @click="finishGroupRegistration"
        v-if="groupActiveTab === 'personInfo' || groupActiveTab === 'addedPersons'"
      >
        提交
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
import { addGroup } from "@/api/training/registration";

export default {
  props: {
    visible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      groupActiveTab: "unitInfo",
      groupTitle: "新增集体报名",
      groupForm: {
        unitName: "",
        socialCreditCode: "",
        administrativeArea: "",
        unitNature: "",
        contact: "",
        unitPhonenumber: ""
      },
      personForm: {
        trainingType: "新训",
        studentName: "",
        phonenumber: "",
        certificateType: "idCard",
        idNumber: "",
        idValidDate: [],
        certificateStarttime: "",
        certificateEndtime: "",
        sex: "男",
        birthDate: "",
        nation: "",
        qualification: "",
        workUnit: "",
        workPeriod: [],
        workResume: "请输入工作简历内容，可自由编辑"
      },
      personList: [],
      groupRules: {
        socialCreditCode: [
          { required: true, message: "请输入统一信用代码", trigger: "blur" }
        ],
        administrativeArea: [
          { required: true, message: "请输入所属区域", trigger: "blur" }
        ],
        unitNature: [
          { required: true, message: "请选择单位性质", trigger: "change" }
        ],
        contact: [
          { required: true, message: "请输入联系人姓名", trigger: "blur" }
        ],
        unitPhonenumber: [
          { required: true, message: "请输入联系电话", trigger: "blur" }
        ]
      },
      archiveLabelToIndexMap: {
        全缺: 0,
        照片: 1,
        申请表: 2,
        身份证: 3,
        学历证明: 4,
        体检证明: 5
      }
    };
  },
  methods: {
    nextStep() {
      this.$refs["groupForm"].validate(valid => {
        if (valid) {
          this.groupActiveTab = "personInfo";
          this.groupTitle = "新增集体报名 - 人员信息";
        }
      });
    },
    prevStep() {
      if (this.groupActiveTab === "personInfo") {
        this.groupActiveTab = "unitInfo";
        this.groupTitle = "新增集体报名";
      } else if (this.groupActiveTab === "addedPersons") {
        this.groupActiveTab = "personInfo";
      }
    },
    continueAddPerson() {
      if (!this.personForm.studentName || !this.personForm.phonenumber || !this.personForm.idNumber) {
        this.$message.warning("请填写姓名、手机号码和证件号码");
        return;
      }

      // 处理证件有效期
      if (Array.isArray(this.personForm.idValidDate) && this.personForm.idValidDate.length === 2) {
        this.personForm.certificateStarttime = this.personForm.idValidDate[0];
        this.personForm.certificateEndtime = this.personForm.idValidDate[1];
      } else {
        this.personForm.certificateStarttime = "";
        this.personForm.certificateEndtime = "";
      }

      this.personList.push({ ...this.personForm });

      // 重置表单
      this.personForm.studentName = "";
      this.personForm.phonenumber = "";
      this.personForm.idNumber = "";
      this.personForm.workPeriod = [];
      this.personForm.workUnit = "";

      this.$message.success("人员信息已保存");
      this.groupActiveTab = "addedPersons";
    },
    addWorkExperience() {
      const workPeriod = this.personForm.workPeriod;
      const workUnit = this.personForm.workUnit;

      if (Array.isArray(workPeriod) && workPeriod.length === 2 && workUnit) {
        const start = workPeriod[0];
        const end = workPeriod[1];
        const newExperience = `${start}至${end}，在${workUnit}从事特种设备安全管理工作`;
        this.personForm.workResume += `\n${newExperience}`;
        this.personForm.workPeriod = [];
        this.personForm.workUnit = "";
      } else {
        this.$message.warning("请完整填写工作时间和工作单位");
      }
    },
    removePerson(index) {
      this.personList.splice(index, 1);
    },
    finishGroupRegistration() {
      if (this.personList.length === 0) {
        this.$message.warning("请至少添加一名人员");
        return;
      }

      // 构造提交数据
      const submitData = {
        unitInfo: { ...this.groupForm },
        personList: this.personList.map(person => {
          return {
            ...person,
            // 处理档案缺失字段
            recordMissing: person.recordMissing
              ? person.recordMissing.map(label => this.archiveLabelToIndexMap[label]).join(",")
              : ""
          };
        })
      };

      addGroup(submitData).then(response => {
        if (response.code === 200) {
          this.$message.success("集体报名成功");
          this.$emit("success");
          this.handleClose();
        } else {
          this.$message.error("集体报名失败: " + response.msg);
        }
      });
    },
    handleClose() {
      this.$emit("update:visible", false);
      this.resetGroupForm();
    },
    resetGroupForm() {
      this.groupActiveTab = "unitInfo";
      this.groupTitle = "新增集体报名";
      this.groupForm = {
        unitName: "",
        socialCreditCode: "",
        administrativeArea: "",
        unitNature: "",
        contact: "",
        unitPhonenumber: ""
      };
      this.personForm = {
        trainingType: "新训",
        studentName: "",
        phonenumber: "",
        certificateType: "idCard",
        idNumber: "",
        idValidDate: [],
        sex: "男",
        workUnit: "",
        workPeriod: [],
        workResume: "请输入工作简历内容，可自由编辑"
      };
      this.personList = [];
      this.$nextTick(() => {
        if (this.$refs.groupForm) this.$refs.groupForm.resetFields();
        if (this.$refs.personForm) this.$refs.personForm.resetFields();
      });
    }
  }
};
</script>
